package cn.smxy.ln.controller;

import cn.smxy.ln.common.lang.Result;
import cn.smxy.ln.service.OssService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author ln
 * @date 2022年09月18日 19:46
 */
@RestController
public class OssController {

    @Autowired
    private OssService ossService;

    @PostMapping("/fileoss")
    public Result uploadOssFile(MultipartFile[] file){
        //获取上传文件 MultipartFile(图片，文件都可以)
        //返回上传到oss的路径
        String url[] = new String[file.length];
        try {
            for (int i = 0; i < file.length; i++){
                IOUtils.toByteArray(file[i].getInputStream()); // 先文件流进行保存，在进行异步调用
            }
            for (int i = 0; i < file.length; i++) {
                url[i] = ossService.uploadFileAvatar(file[i]).get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(url);
    }

    @PostMapping("/upTextandImg")
    public void addPro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("收到上传请求");
        //只获取非文件内容
        //getParm(request);
        //同时获取非文件和文件内容
        getFileAndImgAndParm(request);
    }

    private void getFileAndImgAndParm(HttpServletRequest request) throws ServletException, IOException {
        System.out.println("//获取文件并保存==================");
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断是否是多数据段提交格式
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            System.out.println("以下获取上传的非文件==");
            Map<String, String[]> parameterMap = multiRequest.getParameterMap();
            Set<String> keySet = parameterMap.keySet();
            for (String key : keySet) {
                String[] strings = parameterMap.get(key);
                String msg = Arrays.toString(strings);
                System.out.println(key + "===" + msg);
            }

            System.out.println("以下获取上传的文件==");
            Iterator<String> iter = multiRequest.getFileNames();
            //进入到这。iter中的已经全部是文件类型了
            Integer fileCount = 0;
            while (iter.hasNext()) {
                String next = iter.next();
                Part part = multiRequest.getPart(next);
                String name = part.getName();
                System.out.println(name);
                //TODO
                MultipartFile file = multiRequest.getFile(next);
                System.out.println(file);
                if (file == null) {
                    System.out.println("非文件");
                    return;
                }
                String fileName = UUID.randomUUID() + file.getOriginalFilename();
                File dest = new File(new File("D:\\data").getAbsolutePath() + "/" + fileName);
                if (!dest.getParentFile().exists()) {
                    //新建空白图片
                    dest.getParentFile().mkdirs();
                }
                try {
                    //将图片流写入空白文件
                    file.transferTo(dest); // 保存文件
                    fileCount++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("本次提交文件类型的个数==" + fileCount);
        }
    }

    private void getParm(HttpServletRequest request) {
        System.out.println("两种方法获取非文件类型的值");
        //获取非文件并保存==========================================================================
        Map<String, String> parmMap = new HashMap<String, String>();
        //方式一：getParameterMap()，获得请求参数map
        Map<String, String[]> map = request.getParameterMap();
        //参数名称
        Set key = map.keySet();
        //参数迭代器
        Iterator iterator = key.iterator();
        while (iterator.hasNext()) {
            String k = String.valueOf(iterator.next());
            parmMap.put(k, map.get(k)[0]);
        }
        System.out.println("parmMap==========" + parmMap);

        //方式二：getParameterNames()：获取所有参数名称
        Enumeration a = request.getParameterNames();
        String parm = null;
        String val = "";
        while (a.hasMoreElements()) {
            //参数名
            parm = String.valueOf(a.nextElement());
            //值
            val = request.getParameter(parm);
            parmMap.put(parm, val);
        }
        System.out.println("parmMap==========" + parmMap);
    }
}
